<?php
namespace Sfsn\Lib;

/**
 * xml操作类
 *

$data = [
    'a'=>'a',
    'b'=>'<dfs>',
    'c',
    'd'=>['da'=>1,2]
];

$xml = new Xml();
$xmlString = $xml->toXml($data,'utf-8');
echo $xmlString;
var_dump($xml->toObject($xmlString));
var_dump($xml->toArray($xmlString));
*/
class Xml
{
    /**
     * XML编码
     *
     * @param mixed $data
     *            数据
     * @param string $encoding
     *            数据编码
     * @param string $root
     *            根节点名
     * @return string
     */
    public static function toXml($data, $encoding = '', $root = 'xml')
    {
        $xml = $encoding ? '<?xml version="1.0" encoding="' . $encoding . '"?>' : '';
        $xml .= '<' . $root . '>';
        $xml .= self::data_to_xml($data);
        $xml .= '</' . $root . '>';
        return $xml;
    }

    /**
     * 数据XML编码
     *
     * @param mixed $data      
     * @return string
     */
    private static function data_to_xml($data)
    {
        $xml = '';
        foreach ($data as $key => $val) {
            is_numeric($key) && $key = "item id=\"$key\"";
            $xml .= "<$key>";
            if(is_array($val) || is_object($val)){
                $xml .= self::data_to_xml($val);
            }else{
                $xml .= is_numeric($val) ? $val : '<![CDATA['.$val.']]>';
            }            
            list ($key, ) = explode(' ', $key);
            $xml .= "</$key>";
        }
        return $xml;
    }
    
    /**
     * xml转换为对象
     * @param unknown $xmlstring
     * @return SimpleXMLElement
     */
    public static function toObject($xmlstring)
    {
        return simplexml_load_string($xmlstring,'SimpleXMLElement', LIBXML_NOCDATA);       
    }
    /**
     * xml转换为数组
     * @param unknown $xmlstring
     * @return mixed
     */
    public static function toArray($xmlstring)
    {
        $obj = simplexml_load_string($xmlstring,'SimpleXMLElement', LIBXML_NOCDATA);
        return json_decode(json_encode($obj), true);
    }
}
